package com.codeest.geeknews.widget.behaivor;

import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.codeest.geeknews.R;

/**
 * Created by admin on 2017/8/3.
 */

public class CustomBehavior extends CoordinatorLayout.Behavior<ViewPager> {

    private int mActionBarHeight;

    public CustomBehavior(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init(context);
    }

    public CustomBehavior(Context context) {
        init(context);
    }

    private void init(Context context) {
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
        }
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, ViewPager child, View dependency) {
        return dependency instanceof AppBarLayout;
    }

    public boolean onDependentViewChanged(CoordinatorLayout parent, ViewPager child, View dependency) {
        offsetChildAsNeeded(parent, child, dependency);
        return false;
    }

    private void offsetChildAsNeeded(CoordinatorLayout parent, View child, View dependency) {
        if (child instanceof ViewPager) {
            ViewPager viewPager = (ViewPager) child;
            View list = viewPager.findViewById(R.id.view_main);
            if (list != null) {
                final CoordinatorLayout.Behavior behavior =
                        ((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior();
                if (behavior instanceof AppBarLayout.Behavior) {
                    final AppBarLayout.Behavior ablBehavior = (AppBarLayout.Behavior) behavior;
                    AppBarLayout appBarLayout = (AppBarLayout) dependency;
                    ViewCompat.setTranslationY(list, ablBehavior.getTopAndBottomOffset()
                            + appBarLayout.getTotalScrollRange()
                            + mActionBarHeight);
                }
            }
        }
    }
}